#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;
#define EXIT_ERR_CODE(m) \
    do                   \
    {                    \
        perror(m);       \
    exit(EXIT_FAILURE);  \
    } while (0)

const string pathname= ".";
const int projid=0x666;
#define gdefaultid -1
#define gsize 4096
#define gmode 0666
#define CREATER "creater"
#define USER "user"
class shm
{
private:
    void creatshm(int flg)
    {

        _shmid = shmget(_key, _size, flg);
        if (_shmid < 0)
        {
            EXIT_ERR_CODE("shmget");
        }
        printf("shmid:%d", _shmid);
    }
    void creat()
    {
        creatshm(IPC_CREAT | IPC_EXCL | gmode);
    }
    void get()
    {
        creatshm(IPC_CREAT);
    }
    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            EXIT_ERR_CODE("shmat");
        }
    }
    void destory()
    {
        if (_shmid == gdefaultid)
        {
            return;
        }
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if (n == 0)
        {
            printf("success control shm");
        }
        else
        {
            printf("failed");
        };
    }
public:
    shm(const string pathname, const int projid, const string usertype)
        : _shmid(gdefaultid), _size(gsize), _usertype(usertype), _start_mem(nullptr)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            EXIT_ERR_CODE("ftok");
        }
        if (_usertype == CREATER)
        {
            creat();
        }
        else if(_usertype==USER)
        {
            get();
        }
        Attach();
    }

   
    int size()
    {
        return _size;
    }
    void *VirtualAddr()
    {
        printf("%p\n", _start_mem);
        return _start_mem;
    }
    ~shm()
    {
        if(_usertype==CREATER)
        {
            destory();
        }
    }

private:
    int _shmid;
    int _size;
    key_t _key;
    string _usertype;
    void *_start_mem;
};